import {
	auth,
	silenceAuth,
	getUserInfo,
	logout,
	loginByUsername
} from "@/api/user";

import {
	TOKEN,
	REFRESH_TOKEN,
	USER_INFO,
	TENANT_ID,
	QQMAP_KEY
} from '@/config/const';

/**
 * 获取服务供应商
 */
function getProvider() {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: 'oauth',
			success(res) {
				resolve(res.provider);
			},
			fail() {
				resolve(false);
			}
		});
	});
}

export default {
	// 为当前模块开启命名空间
	namespaced: true,
	state: {
		userInfo: {},
		token: false,
		member: [],
		refreshToken: false,
		currentLocation: {
			localCity: '太原市',
			longitude: 112.567492,
			latitude: 37.824599,
			isDefault: true
		},
		qqmapsdk: false,
		currentStoreId: '',
		curretnStore: {},
		shopId: false,
		userAvatar: "http://qichong-1256206693-1256206693.cos.ap-nanjing.myqcloud.com/upload/20210617/a1b0aedabc466612a506a75eda513e72.png",
	},
	mutations: {
		setToken(state, token) {
			state.token = token;
		},
		setMember(state, member) {
			state.member = member;
		},
		setshopId(state, shopId) {
			state.shopId = shopId;
		},
		setRefreshToken(state, refreshToken) {
			state.refreshToken = refreshToken;
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
		},
		setCurrentLocation(state, loc) {
			state.currentLocation = loc
		},
		setCurrentStoreId(state, id) {
			state.currentStoreId = id
		},
		setCurrentStore(state, currStore) {
			state.curretnStore = currStore
		}
	},
	getters: {
		isLogin: state => {
			return (!state.token || state.token === '') ? false : true
		},
		userInfo: state => state.userInfo,
		token: state => state.token,
		currentLocation: state => state.currentLocation,
		currentStoreId: state => state.currentStoreId,
		curretnStore: state => state.curretnStore
	},
	actions: {
		getProvider: function() {
			return new Promise((resolve, reject) => {
				uni.getProvider({
					service: 'oauth',
					success(res) {
						resolve(res.provider);
					},
					fail() {
						resolve(false);
					}
				});
			});
		},
		getCode: function() {
			return new Promise((resolve, reject) => {
				let provider = getProvider();
				uni.login({
					provider: provider,
					success(res) {
						return resolve(res.code);
					},
					fail() {
						return reject(null);
					}
				})
			})
		},
		loginByUsername: function({
			commit,
			dispatch
		}, userInfo) {
			return new Promise((resolve, reject) => {
				loginByUsername(userInfo.avatarUrl, userInfo.nickName, userInfo.city,
					userInfo.country, userInfo.province, userInfo.gender,
					userInfo.code,
					userInfo.registType, 'app', userInfo.spreadId).then(res => {
					if (res.error_description) {
						reject(res.error_description);
					} else {
						commit('setToken', res.access_token);
						commit('setRefreshToken', res.refresh_token);
						dispatch('getUserInfo');
						dispatch('m_pet/GetRecordItem', {}, {
							root: true
						});
						dispatch('m_pet/GetUserVipItem', {}, {
							root: true
						});
					}
					resolve();
				}).catch(error => {
					reject(error);
				})
			})
		},

		/**
		 * 小程序新登录方式
		 */
		loginByWxNewMiniapp: function({
			commit,
			dispatch
		}, userInfo) {
			return new Promise((resolve, reject) => {
				auth(userInfo.encryptedData, userInfo.iv,
					userInfo.code,
					2, 'app', userInfo.spreadId).then(res => {
					if (res.error_description) {
						reject(res.error_description);
					} else {
						commit('setToken', res.access_token);
						commit('setRefreshToken', res.refresh_token);
						dispatch('getUserInfo');
						dispatch('m_pet/GetRecordItem', {}, {
							root: true
						});
						dispatch('m_pet/GetUserVipItem', {}, {
							root: true
						});
					}
					resolve();
				}).catch(error => {
					reject(error);
				})
			})
		},
		loginBySilenceAuth: function({
			commit,
			dispatch
		}, data) {
			return new Promise((resolve, reject) => {
				silenceAuth(data.code, 2, data.spreadId).then(res => {
					if (res.error_description) {
						// reject(res.error_description);
					} else {
						// console.log(res)
						commit('setToken', res.access_token);
						commit('setRefreshToken', res.refresh_token);
						// commit('setUserInfo', res);
						dispatch('getUserInfo');
						dispatch('m_pet/GetRecordItem', {}, {
							root: true
						});
						dispatch('m_pet/GetUserVipItem', {}, {
							root: true
						});
					}
					resolve();
				}).catch(error => {
					// reject(error);
				})
			})
		},
		//获取用户信息
		getUserInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getUserInfo().then((res) => {
					commit('setUserInfo', res.data);
					resolve();
				}).catch(err => {
					// reject(err);
				})
			})
		},
		//刷新token
		refreshToken({
			state,
			commit
		}) {
			return new Promise((resolve, reject) => {
				auth({
					grant_type: "refresh_token",
					scope: 'all',
					refresh_token: state.refreshToken,
					tenantId: TENANT_ID
				}).then(res => {
					const data = res.data;
					commit('setToken', data.access_token);
					commit('setRefreshToken', data.refresh_token);
					resolve();
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登出
		LogOut({
			commit
		}) {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					commit('setToken', false);
					commit('setUserInfo', {});
					resolve();
				}).catch(error => {
					reject(error)
				})
			})
		},
		//获取当前位置
		getCurrentLocation({
			state,
			commit
		}) {
			return new Promise((resolve, reject) => {

				uni.getLocation({
					// #ifdef APP-PLUS || MP
					type: 'gcj02',
					// #endif
					success(loc) {
						location = {
							latitude: loc.latitude,
							longitude: loc.longitude,
							isDefault: false
						};
						commit('setCurrentLocation', location);
						resolve(location);
					},
					fail(res) {
						// reject(res);
						// console.log('222')
						uni.showModal({
							title: '请求授权当前位置',
							content: '需要获取您的地理位置，请确认授权',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting(); // 打开地图权限设置
								} else if (res.cancel) {
									uni.showToast({
										title: '你拒绝了授权，无法获得周边信息',
										icon: 'none',
										duration: 1000
									})
								}
							}
						});
					}
				})
			})
		}
	}
}
